import frappe
import requests

def dingding_enabled(doc):
    return frappe.get_single("Selling Settings").get("custom_enable_dingding_notification", 0)

# 发送钉钉通知的函数
def send_dingding_notification(doc):
    #frappe.log_error("开始发送钉钉通知", "钉钉通知日志")  # 在发送通知前添加日志
    # 获取当前文档的工作流状态
    workflow_state = doc.workflow_state
    
    # 获取工作流配置
    workflow = frappe.get_doc("Workflow", {"document_type": doc.doctype})
    
    # 找到当前状态的位置
    current_state_index = None
    for i, state in enumerate(workflow.states):
        if state.state == workflow_state:
            current_state_index = i
            break

    # 获取下一步状态的角色
    next_approval_roles = []
    if current_state_index is not None and current_state_index + 1 < len(workflow.states):
        # 获取下一步的状态
        next_state = workflow.states[current_state_index + 1]
        next_approval_roles = next_state.allow_edit or []
    
    # 根据角色获取用户完整姓名
    if next_approval_roles:
        users = frappe.get_all("Has Role", filters={"role": ["in", next_approval_roles]}, fields=["parent"])
        user_names = [
            frappe.db.get_value("User", user["parent"], "full_name")
            for user in users if frappe.db.get_value("User", user["parent"], "enabled")
        ]
        next_approvers = ", ".join(user_names) if user_names else "无审批人"
    else:
        next_approvers = "无审批人"
    # 构建钉钉消息内容
    # 针对 Stock Manager 的情况
    if next_approval_roles == "Stock Manager":
        pass

    # 针对 Sales Manager 的情况
    elif next_approval_roles == "Sales Manager":
        if doc.customer_group == "售后市场":
            if "吴小星" in next_approvers:
                next_approvers = "吴小星"
            else:
                # 如果不是吴小星，保持原值或设置默认值
                next_approvers = next_approvers  # 保持原值
                # 或者
                # next_approvers = "无符合条件的审批人"  # 如果需要默认值
        else:
            if "沈立" in next_approvers:
                next_approvers = "沈立"

    # 针对 sales master manager 的情况
    elif next_approval_roles == "Sales Master Manager":
        if "沈立" in next_approvers:
            next_approvers = "沈立"
        else:
            # 如果不是沈立，保持原值或设置默认值
            next_approvers = next_approvers  # 保持原值
            # 或者
            # next_approvers = "无符合条件的审批人"  # 如果需要默认值

    # 如果没有匹配到任何条件，可以处理其他情况
    else:
        # 这里可以为 next_approvers 赋一个默认值
        next_approvers = next_approvers  # 保持原值
        # 或者
        # next_approvers = "无符合条件的审批人"  # 如果需要默认值

    # 获取销售出库单对应的销售订单
    sales_order = frappe.db.get_value("Delivery Note Item", {"parent": doc.name}, "against_sales_order")

    # 获取销售订单的创建人
    sales_order_owner = None
    if sales_order:
        sales_order_owner = frappe.db.get_value("Sales Order", sales_order, "owner")

    sales_order_owner_name = frappe.db.get_value("User", sales_order_owner, "full_name") if sales_order_owner else "无销售订单"

    # 如果销售订单创建人是 "濮梦婷"，改为 "沈立"
    if sales_order_owner_name == "濮梦婷":
        sales_order_owner_name = "沈立"

    #frappe.log_error(f"销售订单 {sales_order} 的创建人: {sales_order_owner_name}", "销售出库单关联的销售订单创建人")

    # 构建钉钉消息内容
    message = {
        "msgtype": "markdown",
        "markdown": {
            "title": "销售出库确认",
            "text": (
                f"### 销售出库确认\n\n"
                f"销售出库单号：[{doc.name}]({frappe.utils.get_url_to_form(doc.doctype, doc.name)})\n\n"
                f"客户名称: {doc.customer_name}\n\n"
                f"销售员: {sales_order_owner_name}\n\n"  # 替换销售员字段
                f"合计金额: {doc.currency} {doc.grand_total}\n\n"
                f"出库日期: {doc.posting_date}\n\n"
                f"**下一步审批人: <font color=#FF0000>{next_approvers}</font>**"
            )
        },
        "at": {
            "atMobiles": ["13588053040"],
            "isAtAll": True
        }
    }
    
    # Webhook URL
    webhook_url = "https://oapi.dingtalk.com/robot/send?access_token=a7b5b3fe7fd4e54c831425d8f9288b37b713fa727d9d9d022a29c77f1af4347a"
    
    # 在发送钉钉通知之前，检查是否启用了通知
    if not dingding_enabled(doc):
        return

    # 发送 Webhook 请求
    response = requests.post(webhook_url, json=message)

    # if response.status_code == 200:
    #     frappe.log_error(f"钉钉通知发送成功: {response.text}", "钉钉通知成功")
    # else:
    #     frappe.log_error(f"钉钉通知发送失败: {response.text}", "钉钉通知错误")

# 监听文档更新的钩子函数
def on_update_sales_out(doc, method):
    if doc.docstatus == 2:  # 如果单据状态为取消
        return  # 跳过通知逻辑
    # 获取 custom_previous_status 字段值
    custom_previous_status = doc.custom_previous_status

    # 如果 custom_previous_status 为 1, 2, 3, 或 4 时，都发送钉钉通知
    if custom_previous_status not in ["11", "1"]:
        if custom_previous_status in ["2", "3", "4"]:
            # 当 custom_previous_status 为 2 时，必须检查单据状态为 1 才发送通知
            if custom_previous_status == "2":
                if doc.docstatus == 1:  # 仅当单据状态为 1 时发送通知
                    send_dingding_notification(doc)  # 发送通知
            elif custom_previous_status == "4":
                # 当 custom_previous_status 为 4 时，发送已完成审批通知
                message = {
                    "msgtype": "markdown",
                    "markdown": {
                        "title": "已完成审批，请安排出货！",
                        "text": (
                            f"### 已完成审批，请安排出货！\n\n"
                            f"销售出库单号：[{doc.name}]({frappe.utils.get_url_to_form(doc.doctype, doc.name)})\n\n"
                            f"客户名称: {doc.customer_name}\n\n"
                        )
                    },
                    "at": {
                        "atMobiles": ["13588053040"],
                        "isAtAll": True
                    }
                }
                # 发送 Webhook 请求
                webhook_url = "https://oapi.dingtalk.com/robot/send?access_token=a7b5b3fe7fd4e54c831425d8f9288b37b713fa727d9d9d022a29c77f1af4347a"

                # 在发送钉钉通知之前，检查是否启用了通知
                if not dingding_enabled(doc):
                    return

                response = requests.post(webhook_url, json=message)

            else:
                # 当 custom_previous_status 为 3 时，不需要检查 docstatus，直接发送通知
                send_dingding_notification(doc)  # 发送通知

            # 更新状态，标记为已通知
            doc.custom_previous_status = "11"
            doc.save()
            frappe.db.commit()